package com.lejin.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.lejin.JwtUtils;
import com.lejin.RsaUtils;
import com.lejin.usercenter.entity.SysUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
@Component
@RefreshScope
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @Value("${source.white}")
    private String whiteStr;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //校验jwt令牌
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获得用户的请求地址
        String path = request.getPath().toString();
        //放行白名单

        for (String white:whiteStr.split(",")){
            System.out.println("white:"+white+"====="+"path:"+path);


            if (Pattern.matches(white,path)){

                return chain.filter(exchange);


            }
        }


        //受限资源
        //从请求头获取jwt令牌
        String token = request.getHeaders().getFirst("token");
        System.out.println("获取token");

        if (token==null || "".equals(token)){

            //拒绝访问
            Map res = new HashMap(){{
                put("success",false);
                put("msg","令牌不能为空");
            }};
            return response(response,res);
        }

        //解析jwt令牌
        try {
            //令牌合法
            String path1 = ResourceUtils.getFile("classpath:rsa_pub").getPath();
            PublicKey publicKey = RsaUtils.getPublicKey(path1);
            SysUser fromToken = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);

            System.out.println(fromToken);
            String userId = fromToken.getUserId();

            if (userId==null){
                Map res = new HashMap(){{
                    put("success",false);
                    put("msg","用户id不存在");
                }};
                return response(response,res);
            }

            //将用户id放入请求头中
            ServerHttpRequest newRequest = request.mutate().header("userId", userId).build();
            ServerWebExchange exchange1 = exchange.mutate().request(newRequest).build();

            return chain.filter(exchange1);
        } catch (Exception e) {
            Map res = new HashMap(){{
                put("success",false);
                put("msg","非法令牌");
            }};
            return response(response,res);
        }

    }

    //响应
    private Mono<Void>  response(ServerHttpResponse response,Object msg){
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String resJson = JSONUtil.toJsonStr(msg);
        DataBuffer dataBuffer = response.bufferFactory().wrap(resJson.getBytes());
        return response.writeWith(Flux.just(dataBuffer));//响应json数据
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
